<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Document</title>
  <link rel="preload" as="script" href="./scripts/math.js">
  <script>

    var obj ={};

    /**
   * 按需加载JS
   * @param {string} url 脚本地址
   * @param {function} callback  回调函数
   */
     function dynamicLoadJs(url, callback) {
       if(obj[url]){
         callback();
         return;
       }
       obj[url]=true;
      var head = document.getElementsByTagName('head')[0]
      var script = document.createElement('script')
      script.type = 'text/javascript'
      script.src = url
      if (typeof (callback) === 'function') {
        script.onload = script.onreadystatechange = function () {
          if (!this.readyState || this.readyState === 'loaded' || this.readyState === 'complete') {
            callback()
            script.onload = script.onreadystatechange = null
          }
        }
      }
      head.appendChild(script)
    }
  </script>
</head>

<body>


  <button id="btn">load</button>


  <script>

    document.getElementById('btn').addEventListener('click', function () {
      dynamicLoadJs('./scripts/math.js', function () {
        alert(sum(1, 2))
      })
    })

  </script>


</body>

</html>